python转换html到pdf文件

您所在的位置:网站首页 python pdf转html python转换html到pdf文件

python转换html到pdf文件

#python转换html到pdf文件| 来源: 网络整理| 查看: 265

1.安装wkhtmltopdf 

Windows平台直接在 http://wkhtmltopdf.org/downloads.html 下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程序的执行路径加入到系统环境 $PATH 变量中,否则 pdfkit 找不到 wkhtmltopdf 就出现错误 “No wkhtmltopdf executable found”

2.安装pdfkit

直接pip install pdfkit

pdfkit 是 wkhtmltopdf 的Python封装包

1 import pdfkit 2 3 # 有下面3中途径生产pdf 4 5 pdfkit.from_url('http://google.com', 'out.pdf') 6 7 pdfkit.from_file('test.html', 'out.pdf') 8 9 pdfkit.from_string('Hello!', 'out.pdf')

3.合并pdf,使用PyPDF2

直接pip install PyPDF2

1 from PyPDF2 import PdfFileMerger 2 merger = PdfFileMerger() 3 input1 = open("1.pdf", "rb") 4 input2 = open("2.pdf", "rb") 5 merger.append(input1) 6 merger.append(input2) 7 # 写入到输出pdf文档中 8 output = open("hql_all.pdf", "wb") 9 merger.write(output)

4.综合示例:

1 # coding=utf-8 2 import os 3 import re 4 import time 5 import logging 6 import pdfkit 7 import requests 8 from bs4 import BeautifulSoup 9 from PyPDF2 import PdfFileMerger 10 11 html_template = """ 12 13 14 15 16 17 18 {content} 19 20 21 22 """ 23 24 25 def parse_url_to_html(url, name): 26 """ 27 解析URL,返回HTML内容 28 :param url:解析的url 29 :param name: 保存的html文件名 30 :return: html 31 """ 32 try: 33 response = requests.get(url) 34 soup = BeautifulSoup(response.content, 'html.parser') 35 # 正文 36 body = soup.find_all(class_="x-wiki-content")[0] 37 # 标题 38 title = soup.find('h4').get_text() 39 40 # 标题加入到正文的最前面,居中显示 41 center_tag = soup.new_tag("center") 42 title_tag = soup.new_tag('h1') 43 title_tag.string = title 44 center_tag.insert(1, title_tag) 45 body.insert(1, center_tag) 46 html = str(body) 47 # body中的img标签的src相对路径的改成绝对路径 48 pattern = "(


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3